package com.id.coinscleaner.scared

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.app.Activity
import android.app.Service
import android.content.Intent
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Bundle
import android.os.Vibrator
import android.view.View
import android.widget.Toast
import androidx.annotation.RawRes
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.id.coinscleaner.App.Companion.DataStore
import com.id.coinscleaner.Main2Activity
import com.id.coinscleaner.R
import com.id.coinscleaner.adapters.ScaredAdapter
import com.id.coinscleaner.common.ViewBindingActivity
import com.id.coinscleaner.databinding.ActivityScaredBinding
import com.id.coinscleaner.utils.*
import com.id.coinscleaner.viewmodel.ScaredViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

private const val NoPermissionComeInOnce = "NoPermissionComeInOnce"


<<<<<<< HEAD
class ScaredActivity : ViewBindingActivity<ActivityScaredBinding>() {

    //订阅标志位
=======
>>>>>>> 65dd7ef4291bce327bf4a6acb247be4d8b45e92b
    val hasPermission = hasWriteStoragePermission && hasWriteStoragePermission
    val viewModel by lazy { ViewModelProvider(this).get(ScaredViewModel::class.java) }
    val animationSet = AnimatorSet()
    val adapter by lazy { ScaredAdapter() }
    val contentResolver = ScreenshotContentResolver()
    private var vibrator: Vibrator? = null
    private val soundPool by lazy {
        SoundPool.Builder().apply {
            setMaxStreams(1)
            val attrBuilder = AudioAttributes.Builder()
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC)
            setAudioAttributes(attrBuilder.build())
        }.build()
    }


    override fun onInit(savedInstanceState: Bundle?) {
        //防止用户截屏
        Events.sendEvent(if (hasPermission) "storage_access_yes" else "storage_access_no")
        Events.sendEvent("vr_scan_page")
        DataStore.encode(NoPermissionComeInOnce, true)//第一次进入页面
        contentResolver.register()
        viewModel.initScaredData()
        playSound(R.raw.alarm)
        binding.scaredRV.layoutManager = LinearLayoutManager(this)
        binding.scaredRV.adapter = adapter
        //逐步插入数据
        binding.ScanProgressView.setProgress(0f)
        binding.ScanProgressView.startAnimate(((viewModel.scareData.size) * 200).toLong())
        Events.sendEvent("v_scanning_page")

        lifecycleScope.launch {
            viewModel.scareData.forEach { scaredItem ->
                delay(200)
                adapter.data.add(scaredItem)
                adapter.notifyDataSetChanged()
                binding.scaredRV.smoothScrollToPosition(adapter.data.size - 1)
                if (ScreenshotContentResolver.isScreenshot) {
                    finish()
                }
            }
            changeWarning()
        }

        binding.removebtn.setOnClickListener {
            Events.sendEvent("click_remove")
            this.pay(lifecycleScope)
        }
    }


    fun changeWarning() {
        binding.titleConsraintLayout.background = getDrawable(R.drawable.warn_upround_bg)
        binding.redThreeTv.visibility = View.VISIBLE
        binding.fdIg.setImageResource(R.drawable.ic_warn_scan)
        binding.svIg.setImageResource(R.drawable.wning)
        binding.warnConstraintLayout.visibility = View.VISIBLE
        val animatorX = ObjectAnimator.ofFloat(binding.removebtn, "scaleX", 0.8f, 1.0f)
        animatorX.repeatCount = ObjectAnimator.INFINITE
        animatorX.repeatMode = ObjectAnimator.REVERSE
        val animatorY = ObjectAnimator.ofFloat(binding.removebtn, "scaleY", 0.8f, 1.0f)
        animatorY.repeatCount = ObjectAnimator.INFINITE
        animatorY.repeatMode = ObjectAnimator.REVERSE
        animationSet.apply {
            playTogether(animatorX, animatorY)
            start()
        }
    }


    fun stopSound() {
        pauseVibrator()
        soundPool.autoPause()
    }

<<<<<<< HEAD
    suspend fun startRemoving() {
=======
    suspend fun startremoving() {
>>>>>>> 65dd7ef4291bce327bf4a6acb247be4d8b45e92b
        Events.sendEvent("v_removing_page")
        animationSet.apply {
            removeAllListeners()
            end()
            cancel()
        }
        stopSound()
        binding.removebtn.setImageResource(R.drawable.removing)
        val removeList = listOf(3, 9, 13, 17, 26)
        var threatNum = binding.redThreeTv.text.toString().toInt()
        removeList.forEach {
            adapter.removeItem(it)
            binding.scaredRV.smoothScrollToPosition(it)
            delay(300)
            threatNum--
            binding.redThreeTv.text = threatNum.toString()
        }
    }


    suspend fun completeRemoving() {
        binding.wholeLayout.visibility = View.GONE
        binding.completedConstaintLayout.visibility = View.VISIBLE
        delay(1000)
        finish()
<<<<<<< HEAD
        startActivity(Intent(this@ScaredActivity, MainActivity::class.java))
=======
        startActivity(Intent(this@ScaredActivity, Main2Activity::class.java))
>>>>>>> 65dd7ef4291bce327bf4a6acb247be4d8b45e92b
        Events.sendEvent("v_removed")
    }

    override fun onDestroy() {
        super.onDestroy()
        stopSound()
        contentResolver.unregister()
    }

    private fun playVibrator() {
        vibrator?.vibrate(longArrayOf(0, 500, 2000, 500), 0)
    }

    private fun pauseVibrator() {
        vibrator?.cancel()
    }

    private fun playSound(@RawRes resId: Int) {
        val voiceId = soundPool.load(this, resId, 1)
        soundPool.setOnLoadCompleteListener { soundPool, _, status ->
            if (status == 0) {
                vibrator = getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
                playVibrator()
                soundPool.play(voiceId, 1f, 1f, 1, -1, 1f)
            }
        }
    }

    //屏蔽返回键
    override fun onBackPressed() {

    }


    private fun Activity.pay(coroutineScope: CoroutineScope) {
<<<<<<< HEAD
        val subSku = SubSku.findSubSkuBySkuId(SubSku.SkuYearly.skuId)
=======

        val subSku = SubSku.findSubSkuBySkuId(SubSku.SkuWeekly.skuId)
>>>>>>> 65dd7ef4291bce327bf4a6acb247be4d8b45e92b
        coroutineScope.launch {
            pay(subSku).onStart {
                Events.sendEvent("v_start_sub_${subSku.skuId}", "reason" to subSku.skuId)
            }.catch {
                Events.sendEvent("v_sub_fail_${subSku.skuId}", "reason" to it.message)
                if (it !is UserCanceledPayException) {
                    Toast.makeText(this@pay, "Network Error", Toast.LENGTH_SHORT).show()
                }
            }.collect {
<<<<<<< HEAD
                Events.sendEvent("v_sub_seccessful${subSku.skuId}")
                //处理订阅完之后的逻辑
                startRemoving()
=======
                Events.sendEvent("v_sub_successful${subSku.skuId}")
                //处理订阅完之后的逻辑
                startremoving()
>>>>>>> 65dd7ef4291bce327bf4a6acb247be4d8b45e92b
                completeRemoving()
            }
        }
    }

}